package com.fan.shop.dao;

import java.util.List;

import javax.inject.Named;

import org.hibernate.SessionFactory;

import com.fan.shop.domain.User;
import com.fan.shop.global.ShopGlobalVariables;

@Named("userDao")
public class UserDaoImpl implements UserDao {

	private SessionFactory sessionFactory;

	/**
	 * Get Hibernate Session Factory
	 * 
	 * @return SessionFactory - Hibernate Session Factory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Set Hibernate Session Factory
	 * 
	 * @param SessionFactory
	 *            - Hibernate Session Factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public User getUser(String username) {
		User user = (User) getSessionFactory().getCurrentSession().get(
				User.class, username);
		return user;
	}

	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
		List<User> list = getSessionFactory().getCurrentSession()
				.createQuery("from User").list();

		return list;
	}

	public int getSize() {
		return getAllUsers().size();
	}

	public void addUser(User user) {
		getSessionFactory().getCurrentSession().save(user);

	}

	public void updateUser(User user) {
		getSessionFactory().getCurrentSession().update(user);

	}

	public void deleteUser(User user) {
		getSessionFactory().getCurrentSession().delete(user);
	}

	public boolean hasUser(String username) {
		if (getUser(username) != null) {
			return true;
		} else {
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	public List<String> getColumnNames() {
		List<String> columns = sessionFactory
				.getCurrentSession()
				.createSQLQuery(
						"SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'USER' AND TABLE_SCHEMA = '"
								+ ShopGlobalVariables.DATABASE_NAME + "'")
				.list();

		return columns;
	}

}
